<template>
  <div class="follow-page">
    <!-- 动态列表 -->
    <div v-for="(item, index) in followList" :key="item.userId" class="post-item">
      <!-- 发布者信息 -->
      <div class="post-header">
        <img :src="item.userAvatar" alt="avatar" class="avatar" @click="FriendsHomepagePage(item.userId)" />
        <span class="username">@{{ item.userNickname }}</span>
      </div>

      <!-- 内容描述 -->
      <div class="post-meta">{{ item.videoDesc }}</div>

      <!-- 媒体内容（视频） -->
      <!-- 视频容器 -->
      <div class="post-media" @click="togglePlay(index)">
        <video ref="videoRefs" class="media-video" :src="item.videoPath" preload="metadata" playsinline
          webkit-playsinline x5-playsinline loop :muted="false"></video>

        <!-- 播放/暂停覆盖层 -->
        <div v-if="videoStates[index] === 'paused'" class="play-overlay">
          <Icon name="zantingtubiao" color="#fff" size="32" />
        </div>
      </div>

      <!-- 互动按钮 -->
      <div class="post-actions">
        <div class="action-item" @click.stop="handleLikeClick(item)">
          <Icon name="xin-2" :color="item.isLiked ? '#ff4d4f' : '#fff'" size="20" />
          <span class="count">{{ item.likeNum }}</span>
        </div>
        <div class="action-item" @click.stop="handleCommentClick(item)">
          <Icon name="pinglun" color="#fff" size="20"></Icon>
          <span class="count">{{ item.commentNum }}</span>
        </div>
        <div class="action-item">
          <Icon name="a-fenxiangweifenxiang" color="#fff" size="18"></Icon>
          <span class="count">{{ item.shareNum }}</span>
        </div>
      </div>

      <!-- 时间 -->
      <div class="post-time">{{ item.createdAt }}</div>
    </div>
    <!-- 评论弹窗 -->
    <CommentModal v-if="showCommentModal" v-model="showCommentModal" :videoId="videoCommentsVideoId" />
  </div>
</template>

<script setup>
import { computed, onMounted, ref, defineAsyncComponent, inject, defineOptions } from 'vue'
import Icon from '@/components/common/Icon.vue'
import { getFollowListAPI, followAPI, getFollowVideoLikeStatusAPI } from '@/api/follow'
import { useUserStore } from '@/stores/userinfo'
import { formatTimeAgo } from '@/utils/time'
const socket = inject('socket')
defineOptions({
  name: 'Follow',
})



const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId || '')

// 存储处理后的数据
const followList = ref([])


// 获取关注列表并合并数据

const getFollowList = async () => {
  try {
    const res = await getFollowListAPI(userId.value)
    if (res.code !== 200) throw new Error('获取关注列表失败')

    // 第一步：初步合并基础数据
    let mergedList = res.data.map(item => ({
      ...item.Video,
      ...item.WSLCNum,
      userAvatar: 'http://43.138.15.137:3000' + item.Video.userAvatar,
      createdAt: formatTimeAgo(item.Video.createdAt),
      likeNum: Number(item.WSLCNum.likeNum) || 0,
      isLiked: false, // 先默认 false，后面覆盖
    }))

    // 第二步：为每个视频获取 isLiked 状态（并行请求）
    const likeStatusPromises = mergedList.map(item =>
      getFollowVideoLikeStatusAPI(userId.value, item.videoId)
        .then(statusRes => {
          // 假设接口返回 { code: 200, data: true } 或 { data: false }
          return statusRes.code === 200 ? Boolean(statusRes.data) : false
        })
        .catch(() => false)
    )

    const likeStatusList = await Promise.all(likeStatusPromises)

    // 第三步：把 isLiked 合并回去
    mergedList = mergedList.map((item, index) => ({
      ...item,
      isLiked: likeStatusList[index]
    }))

    followList.value = mergedList
    console.log('最终列表:', followList.value)
  } catch (error) {
    console.error('获取关注列表失败:', error)
  }
}
// 所有 video 元素的 ref
const videoRefs = ref([])


// 切换播放/暂停
const videoStates = ref({})

const togglePlay = async (index) => {
  const video = videoRefs.value[index]
  if (!video) return

  const currentState = videoStates.value[index] || 'idle'

  if (currentState === 'playing') {
    // 播放 → 暂停
    video.pause()
    videoStates.value[index] = 'paused'
  } else {
    // 暂停 或 idle → 播放
    // 暂停所有其他视频，并重置为 idle（隐藏图标）
    videoRefs.value.forEach((v, i) => {
      if (v && i !== index) {
        v.pause()
        videoStates.value[i] = 'idle'
      }
    })

    try {
      await video.play()
      videoStates.value[index] = 'playing'
    } catch (err) {
      console.warn('播放失败:', err)
      videoStates.value[index] = 'idle'
    }
  }
}
// 评论弹窗
const showCommentModal = ref(false)
const videoCommentsVideoId = ref('')
const CommentModal = defineAsyncComponent(() => import('@/components/common/CommentModal.vue'))
// 打开评论
const handleCommentClick = async ({ videoId }) => {
  videoCommentsVideoId.value = videoId
  showCommentModal.value = true
}

// 视频点赞
const handleLikeClick = async ({ videoId, userId: targetUserId }) => {
  const video = followList.value.find(v => v.videoId === videoId)
  if (!video) return

  // 乐观更新：先更新 UI
  const prevLiked = video.isLiked
  const prevLikeNum = video.likeNum

  if (prevLiked) {
    // 取消点赞
    video.isLiked = false
    video.likeNum = Math.max(0, video.likeNum - 1)
  } else {
    // 点赞
    video.isLiked = true
    video.likeNum += 1
  }

  try {
    const res = await followAPI(userId.value, videoId)
    socket.emit('sendTriggerLike', { toUserId: targetUserId })
    console.log('发送点赞触发事件:', { toUserId: targetUserId })
    if (res.code !== 200) {
      throw new Error('请求失败')
    }
    // 成功：无需更新 likeNum（已乐观更新），但可校验 message
    console.log(res.data) // "喜欢成功" 或 "取消喜欢成功"
  } catch (error) {
    // 失败：回滚
    video.isLiked = prevLiked
    video.likeNum = prevLikeNum
    console.error('点赞失败:', error)
  }
}

onMounted(() => {
  getFollowList()
})
import { useRouter } from 'vue-router'
const router = useRouter()
// 跳转到好友主页
const FriendsHomepagePage = (userId) => {
  router.push({ path: '/friends', query: { userId } })
}
</script>

<style lang="scss" scoped>
.follow-page {
  background-color: $secondary-color;
  color: white;
  min-height: 100vh;
  margin-bottom: $spacing-xl;

  .post-item {
    background-color: $bg-color;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: $spacing-lg;

    .post-header {
      @include flex-center;
      gap: 8px;
      margin-bottom: 8px;
      justify-content: start;

      .avatar {
        width: 35px;
        height: 35px;
        border-radius: 50%;
      }

      .username {
        font-size: $font-size-base;
        font-weight: 500;
      }
    }

    .post-meta {
      font-size: $font-size-base;
      color: $comment-modal-border-color;
      margin-bottom: $spacing-md;
    }

    .post-media {
      position: relative;

      overflow: hidden;
      width: 80%;
      height: 400px;
      border-radius: $border-radius-md;
      background-color: $black-color;

      .play-overlay {
        width: 100%;
        height: 100%;
        @include absolute-top-right;
        @include flex-center;
      }

      .media-video {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .post-actions {
      width: 80%;
      @include flex-around;
      margin: $spacing-md 0;
      gap: $spacing-lg;

      .action-item {
        @include flex-center;
        color: $comment-modal-border-color;
        font-size: $font-size-small;
        gap: 5px;
      }
    }
  }
}











.icon-heart {
  color: #ff4d4d;
}

.post-time {
  font-size: $font-size-small;
  color: #999;
  margin-top: $spacing-md;
}

/* 评论区 */
.comment-section {
  margin-top: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-username {
  font-size: 14px;
  font-weight: 500;
}
</style>